package ch.fhnw.edu.rental.daos.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import ch.fhnw.edu.rental.daos.MovieDAO;
import ch.fhnw.edu.rental.model.Movie;

public class JpaMovieDAO implements MovieDAO, ManagedDAO<Movie> {
	
	@PersistenceContext
	private EntityManager em;

	@Override
	public Movie getById(Long id) {
		return this.em.find(Movie.class, id);
	}

	@Override
	public List<Movie> getByTitle(String name) {
		Query q = this.em.createQuery("from Movie m where m.title = :title");
		q.setParameter("title", name);
		return q.getResultList();
	}

	@Override
	public List<Movie> getAll() {
		Query q = this.em.createQuery("from Movie m");
		return q.getResultList();
	}

	@Override
	public void delete(Movie movie) {
		this.em.remove(movie);
	}

	@Override
	public void saveOrUpdate(Movie movie) {
		if (null == movie.getId()) {
			this.em.persist(movie);
		} else {
			this.em.merge(movie);
		}
	}

	@Override
	public Movie manage(Movie instance) {
		return em.merge(instance);
	}
}
